<template>
  <div class="alarm-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-content">
        <div class="search-item">
          <div class="search-label">省份</div>
          <el-select v-model="searchForm.province" placeholder="请选择省份" class="search-input">
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <div class="search-label">流域</div>
          <el-select v-model="searchForm.basin" placeholder="请选择流域" class="search-input">
            <el-option
              v-for="item in basinOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <div class="search-label">监测时间</div>
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="search-input"
          />
        </div>
      </div>

      <div class="search-buttons">
        <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
        <el-button @click="handleReset" class="search-button">重置</el-button>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="button-group">
      <el-button type="primary" class="custom-button" @click="handleAdd">新增参数</el-button>
      <el-button type="danger" class="custom-button" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" class="custom-button" @click="handleExport">导出数据</el-button>
    </div>

    <!-- 告警表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备ID" align="center">
        <template #default="{ row }">
          {{ deviceMap[row.deviceId] || row.deviceId }}
        </template>
      </el-table-column>
      <el-table-column prop="collectTime" label="采集时间" align="center" />
      <el-table-column prop="paramName" label="参数名" align="center" />
      <el-table-column prop="value" label="数值" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default>
          <el-button type="primary" size="small" class="operation-button" @click="handleEdit">
            编辑
          </el-button>
          <el-button type="danger" size="small" class="operation-button" @click="handleDelete">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="custom-pagination">
      <span>共 {{ total }} 条</span>
      <select v-model="pageSize" @change="handleSizeChange" class="page-size-select">
        <option v-for="size in [10, 20, 30, 50]" :key="size" :value="size">{{ size }}条/页</option>
      </select>
      <button
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
        class="pagination-button"
      >
        &lt;
      </button>
      <button
        v-for="page in totalPages"
        :key="page"
        :class="['pagination-button', { 'current-page': page === currentPage }]"
        @click="changePage(page)"
      >
        {{ page }}
      </button>
      <button
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
        class="pagination-button"
      >
        &gt;
      </button>
      <span>前往</span>
      <input
        type="number"
        v-model.number="jumpPage"
        @keyup.enter="jumpToPage"
        class="pagination-input"
        :max="totalPages"
        :min="1"
      />
      <span>页</span>
    </div>

    <!-- 新增告警对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增传感器数据"
      width="30%"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="设备ID" prop="deviceId" required>
          <el-input v-model="formData.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="参数名" prop="paramName" required>
          <el-input v-model="formData.paramName" placeholder="如 temperature" />
        </el-form-item>
        <el-form-item label="数值" prop="value" required>
          <el-input-number
            v-model="formData.value"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSensorDataList, saveSensorData } from '@/api/Alarm'
import { getDeviceList } from '@/api/devicelist'

// 搜索表单数据
const searchForm = reactive({
  province: '',
  basin: '',
  timeRange: [],
})

// 省份选项
const provinceOptions = ref([
  { value: 'beijing', label: '北京' },
  { value: 'shanghai', label: '上海' },
  // 添加更多省份...
])

// 流域选项
const basinOptions = ref([
  { value: 'yangtze', label: '长江流域' },
  { value: 'yellow', label: '黄河流域' },
  // 添加更多流域...
])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const jumpPage = ref(1)

// 设备ID到名称的映射
const deviceMap = ref({})

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.province = ''
  searchForm.basin = ''
  searchForm.timeRange = []
  currentPage.value = 1
  getList()
}

// 获取设备列表并建立映射
const fetchDeviceMap = async () => {
  const res = await getDeviceList({ pageNum: 1, pageSize: 1000 }) // 假设设备不多
  if (res && res.data && Array.isArray(res.data.data)) {
    const map = {}
    res.data.data.forEach((device) => {
      map[device.id] = device.name
    })
    deviceMap.value = map
  }
}

// 获取列表数据
const getList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      // 可根据需要添加筛选条件
    }
    const res = await getSensorDataList(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total || res.data.records.length
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 对话框相关
const dialogVisible = ref(false)
const formRef = ref(null)

// 表单数据
const formData = reactive({
  deviceId: '',
  paramName: '',
  value: null,
})

// 表单验证规则
const rules = {
  deviceId: [{ required: true, message: '请输入设备ID', trigger: 'blur' }],
  paramName: [{ required: true, message: '请输入参数名', trigger: 'blur' }],
  value: [{ required: true, message: '请输入数值', trigger: 'blur' }],
}

// 打开新增对话框
const handleAdd = () => {
  dialogVisible.value = true
  formData.deviceId = ''
  formData.paramName = ''
  formData.value = null
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await saveSensorData(formData)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        getList() // 刷新列表
      } catch {
        ElMessage.error('添加失败')
      }
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm('确认删除选中的告警记录吗？', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      // 实现批量删除逻辑
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 导出数据
const handleExport = () => {
  // 实现导出逻辑
}

// 编辑
const handleEdit = () => {
  // 实现编辑逻辑
}

// 删除
const handleDelete = () => {
  ElMessageBox.confirm('确认删除该告警记录吗？', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      // 实现删除逻辑
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    getList()
  }
}

const jumpToPage = () => {
  if (jumpPage.value < 1) {
    jumpPage.value = 1
  } else if (jumpPage.value > totalPages.value) {
    jumpPage.value = totalPages.value
  }
  currentPage.value = jumpPage.value
  getList()
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchDeviceMap()
  getList() // 你的告警数据获取方法
})
</script>

<script>
export default {
  name: 'AlarmList',
}
</script>

<style scoped lang="scss">
.alarm-list {
  padding: 20px;
  background-color: #f9f9f9; // 与用户管理页面一致

  .search-bar {
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: nowrap;
    margin-bottom: 20px;
    background: none;
    border-radius: 0;

    .search-content {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      flex: none;
    }

    .search-item {
      display: flex;
      align-items: center;
      gap: 5px;

      .search-label {
        white-space: nowrap;
        font-size: 14px;
      }

      .search-input,
      .search-select {
        width: 200px;
      }
    }

    .search-buttons {
      display: flex;
      gap: 10px;
      margin-left: 0;
      align-items: center;
      height: 40px;
    }

    .search-button {
      min-width: 80px;
      padding: 6px 10px;
    }
  }

  .button-group {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-items: center;

    .custom-button {
      white-space: nowrap;
      padding: 5px 10px;
      width: auto;
      min-width: 80px;
      text-align: center;
      border-radius: 4px;
    }
  }

  .operation-button {
    white-space: nowrap;
    padding: 5px 10px;
    width: auto;
    min-width: 60px;
    text-align: center;
    border-radius: 4px;
    margin-right: 5px;
  }

  .custom-pagination {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 20px;
    font-size: 16px;

    span {
      margin: 0 2px;
      line-height: 32px;
    }

    .page-size-select {
      padding: 2px 6px;
      border: none;
      outline: none;
      border-radius: 4px;
      font-size: 14px;
      background-color: #fff;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      width: 120px;
      height: 32px;
      margin-left: 10px;
      margin-right: 6px;
    }

    .pagination-button {
      padding: 2px 6px;
      border: 1px solid #ccc;
      background-color: #fff;
      cursor: pointer;
      border-radius: 4px;
      font-size: 14px;
      min-width: 30px;
      text-align: center;
      transition:
        background-color 0.3s,
        color 0.3s;
      margin-right: 6px;
    }

    .pagination-button:last-of-type {
      margin-right: 0;
    }

    .pagination-button.current-page {
      background-color: #409eff;
      color: #fff;
      border-color: #409eff;
      font-weight: bold;
    }

    .pagination-button:disabled {
      cursor: not-allowed;
      background-color: #f5f5f5;
      color: #ccc;
    }

    .pagination-input {
      width: 40px;
      text-align: center;
      border: 1px solid #ccc;
      border-radius: 4px;
      padding: 2px;
      font-size: 14px;
      height: 30px;
      margin: 0 4px;
    }
  }

  .dialog-form {
    padding: 20px;

    :deep(.el-form-item) {
      margin-bottom: 20px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>
